extends Control

@onready var label:Label = $Label
@onready var bg = $ColorRect

@export var font:Font
@export var maxCharCountPerLine = 10
@export var padding = 2


func _ready():
	hide()


func showMsg(msg:String, pos):
	var lines = []
	var currentLine = ""
	var text = ""
	
	var customFont = font
	var customFontSize = label.label_settings.font_size
	
	for char in msg:
		if char != '\n' and customFont.get_string_size(currentLine + char, 0, -1, customFontSize).x <= maxCharCountPerLine * customFont.get_string_size("好", 0, -1, customFontSize).x:
			currentLine += char
		else:
			currentLine += "\n"
			lines.append(currentLine)
			currentLine = (char + "") if char != '\n' else ""
	
	if currentLine != "": lines.append(currentLine)
	
	var maxLineX = 0
	for line in lines:
		var lineWidth = customFont.get_string_size(line, 0, -1, customFontSize).x
		if lineWidth > maxLineX:
			maxLineX = lineWidth
			
	var totalHeight = customFont.get_height(customFontSize) * lines.size() + (lines.size() - 1) * label.label_settings.line_spacing
	
	var msgSize = Vector2(maxLineX, totalHeight)
	var bgSize = msgSize + Vector2(padding * 2.0, padding * 2.0)
	var labelOffset = Vector2(padding, padding)
	
	for line in lines:
		text += line
		
	label.text = text
	label.size = msgSize
	label.position = labelOffset
	
	bg.size = bgSize
	
	var dialogTentativePosition = pos
	
	var borderMaxView = Vector2(dialogTentativePosition.x + bgSize.x, dialogTentativePosition.y + bgSize.y)
	var leftTopPosView = pos
	
	if borderMaxView.x > Global.viewportWidth:
		var distance = abs(borderMaxView.x - Global.viewportWidth) 
		dialogTentativePosition.x -= distance
	elif leftTopPosView.x < 0:
		var distance = abs(leftTopPosView.x)
		dialogTentativePosition.x += distance
		
	position = dialogTentativePosition
	
	show()
	

